<template>
    <view class="user-container">
        <!-- 顶部背景和用户信息 -->
        <view class="header">
            <view class="user-info">
                <image class="avatar"
                    :src="userInfo.avatar ? (url + userInfo.avatar) : '/static/images/default_avatar.png'"
                    mode="aspectFill" @tap="chooseAvatar" />
                <view class="info-right">
                    <block v-if="userInfo.username">
                        <view class="username">{{ userInfo.username }}</view>
                        <view class="user-id">ID: {{ userInfo.id || '--' }}</view>
                    </block>
                    <button v-else class="login-btn" @tap="goToLogin">立即登录</button>
                </view>
            </view>
        </view>

        <!-- 用户数据统计 -->
        <view class="user-stats">
            <view class="stat-item" @tap="goToOrders()">
                <image src="/static/images/全部订单.png" mode="aspectFit" class="stat-icon" />
                <text class="label">全部订单</text>
            </view>
            <view class="stat-item" @tap="goToPendingpayment()">
                <view class="badge" v-if="pendingPaymentCount > 0">{{ pendingPaymentCount }}</view>
                <image src="/static/images/待付款.png" mode="aspectFit" class="stat-icon" />

                <text class="label">待付款</text>
            </view>
            <view class="stat-item" @tap="goToUndelivered()">
                <image src="/static/images/待发货.png" mode="aspectFit" class="stat-icon" />
                <text class="label">待发货</text>
            </view>
            <view class="stat-item" @tap="goToOrders()">
                <image src="/static/images/待收货.png" mode="aspectFit" class="stat-icon" />
                <text class="label">待收货</text>
            </view>
        </view>

        <!-- 功能菜单 -->
        <view class="menu-section" v-if="userInfo.username">
            <view class="menu-title">我的服务</view>
            <view class="menu-grid">
                <view class="menu-item" @tap="goToAddress">
                    <image src="/static/images/地址管理.png" mode="aspectFit" class="menu-icon" />
                    <text class="menu-label">收货地址</text>
                </view>
                <view class="menu-item" @tap="goToHistory">
                    <image src="/static/images/足迹.png" mode="aspectFit" class="menu-icon" />
                    <text class="menu-label">浏览历史</text>
                </view>
                <view class="menu-item" @tap="goToSetting">
                    <image src="/static/images/setting.png" mode="aspectFit" class="menu-icon" />
                    <text class="menu-label">设置</text>
                </view>
            </view>
        </view>

        <!-- 推荐商品 -->
        <view class="recommend-section">
            <view class="section-title">
                <text class="title">为你推荐</text>
            </view>
            <view class="goods-list">
                <view class="goods-item" v-for="item in recommendList" :key="item.id" @tap="goToDetail(item.id)">
                    <image :src="item.img_url" mode="aspectFill" class="goods-img"></image>
                    <view class="goods-info">
                        <text class="goods-title">{{ item.title }}</text>
                        <view class="price-box">
                            <text class="price">¥{{ item.sell_price }}</text>
                            <text class="buy">{{ item.buy }}人购买</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>

import { useUserStore } from '@/store';
import { storeToRefs } from 'pinia';
import { onLoad, onReachBottom, onShow } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { reqRecommendGoods } from '@/api/index';
import { reqUserOrder } from '@/api/order';

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const url = ('https://letaoapi.jxsaichuang.com/');
const page = ref(1);
const isLoadDone = ref(false);
const pendingPaymentCount = ref(0);//未付款订单数量
// 推荐商品列表
const recommendList = ref([]);
// 监听页面触底事件
onReachBottom(() => {
    if (isLoadDone.value) {
        // 已经加载完毕了，不再往下加载
        return;
    }
    page.value++;
    reqGoodsList();
});
// 登入就获取未付款订单数量，没有登入就不获取
const getPendingPaymentCount = async () => {
    if (userInfo.value.username) {
        const res = await reqUserOrder();
        pendingPaymentCount.value = res.filter(order => order.is_cancel === 0 && order.status === 0).length;
    }

}


// 获取推荐商品
const reqGoodsList = async () => {
    try {
        const res = await reqRecommendGoods(page.value);
        // console.log('获取推荐商品:', res);
        if (res && res.message) {
            // 如果是第一页，直接赋值，否则追加数据
            if (page.value === 1) {
                recommendList.value = res.message;
            } else {
                recommendList.value = [...recommendList.value, ...res.message];
            }
            // 判断是否还有更多数据
            if (res.message.length < 10) {
                // 假设每页10条数据
                isLoadDone.value = true;
            }
        }
    } catch (error) {
        console.error('获取推荐商品失败:', error);
    }
};

// 跳转到商品详情
const goToDetail = (id) => {
    uni.navigateTo({
        url: `/pages/goods_package/goodsdetail/goodsdetail?id=${id}`
    });
};

onLoad(() => {
    reqGoodsList();
});

onShow(() => {
    if (userInfo.value.username) {
        getPendingPaymentCount();
    } else {
        pendingPaymentCount.value = 0;
    }
});


// 选择并上传头像
const chooseAvatar = () => {
    // 检查是否登录
    if (!userInfo.value.username) {
        goToLogin();
        return;
    }
    // 使用uni的选择图片API
    uni.chooseImage({
        count: 1, // 最多可以选择的图片张数
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            const tempFilePath = res.tempFilePaths[0];

            // 显示上传中的提示
            uni.showLoading({
                title: '上传中...',
                mask: true
            });

            // 上传图片
            uni.uploadFile({
                url: 'https://letaoapi.jxsaichuang.com/api/upload',
                filePath: tempFilePath,
                name: 'avatar',
                header: {
                    token: userStore.token
                },
                success: (uploadRes) => {
                    try {
                        const result = JSON.parse(uploadRes.data);
                        console.log('上传结果：', result);
                        if (result.status === 0) {
                            // 更新用户头像，拼接完整的URL
                            userInfo.value.avatar = result.src;
                            uni.showToast({
                                title: result.message || '头像上传成功',
                                icon: 'success'
                            });
                        } else {
                            uni.showToast({
                                title: result.message || '上传失败',
                                icon: 'error'
                            });
                        }
                    } catch (error) {
                        console.error('处理返回数据错误:', error);
                        uni.showToast({
                            title: '上传失败',
                            icon: 'error'
                        });
                    }
                },
                fail: (err) => {
                    console.error('上传失败:', err);
                    uni.showToast({
                        title: '上传失败',
                        icon: 'error'
                    });
                },
                complete: () => {
                    // 无论成功失败都隐藏加载提示
                    uni.hideLoading();
                }
            });
        }
    });
};

// 跳转到登录页
const goToLogin = () => {
    uni.navigateTo({
        url: '/pages/user_package/login/login'
    });
};

// 跳转到设置页
const goToSetting = () => {
    if (!userInfo.value.username) {
        goToLogin();
        return;
    }
    uni.navigateTo({
        url: '/pages/user_package/setting/setting'  // 修正路徑
    });
};

// 跳转到订单页
const goToOrders = () => {
    //如果没有登入，则跳转到登录页
    if (!userInfo.value.username) {
        goToLogin();
        return;
    }
    uni.navigateTo({
        url: `/pages/order_package/order/order`
    });
};
// 跳转到待付款订单页
const goToPendingpayment = () => {
    if (!userInfo.value.username) {
        goToLogin();
        return;
    }
    uni.navigateTo({
        url: `/pages/order_package/order/pendingpayment`
    });
};
// 跳转到待发货订单页
const goToUndelivered = () => {
    if (!userInfo.value.username) {
        goToLogin();
        return;
    }
    uni.navigateTo({
        url: `/pages/order_package/order/undelivered`
    });
};

// 跳转到地址管理页
const goToAddress = () => {
    if (!userInfo.value.username) {
        goToLogin();
        return;
    }
    uni.navigateTo({
        url: '/pages/address_package/address/address?from=user'
    });
};

// 跳转到浏览历史页
const goToHistory = () => {
    if (!userInfo.value.username) {
        goToLogin();
        return;
    }
    uni.navigateTo({
        url: '/pages/user_package/history/history'
    });
};
</script>

<style lang="scss" scoped>
.user-container {
    min-height: 100vh;
    background-color: #f8f8f8;

    .header {
        position: relative;
        padding: 40rpx 30rpx 60rpx;
        background: linear-gradient(135deg, #ff6b00, #ff8c00);

        .user-info {
            display: flex;
            align-items: center;

            .avatar {
                width: 120rpx;
                height: 120rpx;
                border-radius: 50%;
                border: 4rpx solid rgba(255, 255, 255, 0.8);
                box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
            }

            .info-right {
                flex: 1;
                margin-left: 30rpx;

                .username {
                    color: #fff;
                    font-size: 36rpx;
                    font-weight: 500;
                    margin-bottom: 8rpx;
                }

                .user-id {
                    color: rgba(255, 255, 255, 0.8);
                    font-size: 24rpx;
                }
            }
        }
    }

    .user-stats {
        padding: 30rpx 20rpx;
        background-color: #fff;
        display: flex;
        justify-content: space-between;
        border-bottom: 1rpx solid #f5f5f5;

        .stat-item {
            text-align: center;
            flex: 1;
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;

            &:not(:last-child)::after {
                content: '';
                position: absolute;
                right: 0;
                top: 50%;
                transform: translateY(-50%);
                height: 30rpx;
                width: 1rpx;
                background-color: #eee;
            }

            .stat-icon {
                width: 40rpx;
                height: 40rpx;
                margin-bottom: 12rpx;
            }

            .label {
                font-size: 24rpx;
                color: #666;
                line-height: 1;
            }

            .badge {
                position: absolute;
                right: 25rpx;
                top: -20rpx;
                min-width: 32rpx;
                height: 32rpx;
                padding: 0 8rpx;
                //边框
                border: 1rpx solid #f70505;
                color: #f70505;
                font-size: 20rpx;
                //圆圈
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 1;
                transform: scale(0.9);
                box-shadow: 0 2rpx 4rpx rgba(255, 77, 79, 0.2);
            }
        }
    }

    .menu-section {
        margin: 30rpx 20rpx;
        padding: 30rpx;
        background-color: #fff;
        border-radius: 16rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

        .menu-title {
            font-size: 32rpx;
            color: #333;
            font-weight: 500;
            margin-bottom: 30rpx;
        }

        .menu-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20rpx;

            .menu-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 20rpx 0;

                .menu-icon {
                    width: 64rpx;
                    height: 64rpx;
                    margin-bottom: 16rpx;
                }

                .menu-label {
                    font-size: 24rpx;
                    color: #666;
                }
            }
        }
    }

    .recommend-section {
        margin: 20rpx;

        .section-title {
            position: relative;
            padding: 20rpx 30rpx;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;

            &::before,
            &::after {
                content: '';
                flex: 1;
                height: 2rpx;
                background: linear-gradient(to right, transparent, #e4e4e4);
                margin: 0 20rpx;
            }

            &::after {
                background: linear-gradient(to left, transparent, #e4e4e4);
            }

            .title {
                color: #333;
                font-size: 32rpx;
                font-weight: 500;
                white-space: nowrap;
            }
        }

        .goods-list {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20rpx;
            padding: 20rpx;
            box-sizing: border-box;

            // #ifdef H5
            @media screen and (min-width: 768px) {
                grid-template-columns: repeat(3, 1fr);
            }

            @media screen and (min-width: 1024px) {
                grid-template-columns: repeat(4, 1fr);
                max-width: 1200px;
                margin: 0 auto;
            }

            // #endif

            .goods-item {
                background: #fff;
                border-radius: 12rpx;
                margin: 10rpx;
                overflow: hidden;
                box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
                transition: transform 0.3s ease;

                &:hover {
                    transform: translateY(-6rpx);
                }

                .goods-img {
                    width: 100%;
                    height: 320rpx;
                    background-color: #f5f5f5;
                }

                .goods-info {
                    padding: 16rpx;

                    .goods-title {
                        font-size: 28rpx;
                        color: #333;
                        line-height: 1.4;
                        height: 80rpx;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 2;
                        overflow: hidden;
                    }

                    .price-box {
                        margin-top: 16rpx;
                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .price {
                            font-size: 32rpx;
                            color: #ff6b00;
                            font-weight: bold;
                        }

                        .buy {
                            font-size: 24rpx;
                            color: #999;
                            background: #f8f8f8;
                            padding: 4rpx 12rpx;
                            border-radius: 20rpx;
                        }
                    }
                }
            }
        }
    }

    .login-btn {
        height: 64rpx;
        line-height: 64rpx;
        padding: 0 40rpx;
        font-size: 28rpx;
        color: #ff6b00;
        background: #fff;
        border: none;
        border-radius: 32rpx;
        box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);

        &::after {
            border: none;
        }
    }
}
</style>